import { computed, h, reactive, ref } from 'vue';
import { NButton, NSpace, NTag } from 'naive-ui';
import { Layer } from 'slash-layer';
import form from './SysTbDictUpdate.vue';
import httpApi from './httpApi';
// import { authHide } from '@';
import { RowData } from 'naive-ui/es/data-table/src/interface';

const noAllowDeleteIds = new Set<string | number>();
const noAllowEditIds = new Set<string | number>();

/**
 * 视图控制
 */
export const vCtl = reactive({
  addBtn: computed(() => {
    return true && queryForm.value.fkDictGroupCode;
  }),
  updateBtn: computed(() => {
    return true && checkedRows.value.length == 1 && !noAllowEditIds.has(checkedRows.value[0]);
  }),
  delBtn: computed(() => {
    return true && checkedRows.value.length >= 1;
  }),
});
export const initQuery = {};
export const queryForm = ref<any>(JSON.parse(JSON.stringify(initQuery)));
export const tableRef = ref<any>();

export function reloadTable() {
  if (tableRef.value) {
    tableRef.value.reload();
  }
}

/**
 * 选中的数据
 */
export const checkedRows = ref<any>([]);

/**
 * 选中行
 * @param rows
 */
export async function onCheckedRowEvent(rows: any[]) {
  checkedRows.value = rows;
}

export const allowTextEnum = reactive({
  1: {
    text: '允许',
    style: 'info',
  },
  0: {
    text: '禁止',
    style: 'error',
  },
});
export const allowOptions = computed(() => {
  const temp: any = [];
  Object.keys(allowTextEnum).forEach(function (key: any) {
    temp.push({
      value: parseInt(key),
      label: allowTextEnum[key].text,
    });
  });
  return temp.reverse();
});
/**
 * 枚举字段
 */
export const enabledTextEnum = reactive({
  1: {
    text: '启用',
    style: 'info',
  },
  0: {
    text: '禁用',
    style: 'error',
  },
});
export const getEnabledTextEnum = (key: number | string) => {
  return enabledTextEnum[key].text || `--`;
};

export const getEnabledStyleEnum = (key: number | string) => {
  return enabledTextEnum[key].style || `--`;
};
export const enabledOptions = computed(() => {
  const temp: any = [];
  Object.keys(enabledTextEnum).forEach(function (key: any) {
    temp.push({
      value: parseInt(key),
      label: enabledTextEnum[key].text,
    });
  });
  return temp.reverse();
});

/**
 * 更新弹框
 * @param row
 */
export async function doUpdateModal(row: any) {
  if (checkedRows.value.length != 1 && !row) {
    Layer.error('请选择数据条目后操作');
    return;
  }
  if (!row) {
    row = {
      id: checkedRows.value[0],
    };
  }
  await Layer.updateForm({
    title: '编辑字典',
    position: 'sm',
    content: {
      component: form,
      props: { ...row },
    },
  } as any);
  await reloadTable();
}

/**
 * 新增
 * @param row
 */
export async function doSaveModal(row: any) {
  console.log('传递的数据:{}', row);
  await Layer.createForm({
    title: '新增数据字典',
    position: 'sm',
    content: {
      component: form,
      props: {
        fkDictGroupCode: queryForm.value.fkDictGroupCode,
      },
    },
  } as any);
  await reloadTable();
}

/**
 * 删除
 * @param row
 */
export async function doDeleteModal(row: any) {
  let ids: any = [];
  if (!row) {
    ids = [...(checkedRows.value as string[]).filter((id) => !noAllowDeleteIds.has(id))];
  }
  if (row) {
    ids.push(row.id);
  }

  if (ids.length == 0) {
    Layer.error('请选择要删除的且被允许删除的数据条目');
    return;
  }
  await Layer.confirm('您确定删除选中记录么');
  await httpApi.doLogicDeleteEntity(ids);
  await reloadTable();
}

/**
 * 查看表单
 * @param row
 */
export async function doReadModal(row: any) {
  if (checkedRows.value.length != 1 && !row) {
    Layer.error('请选择数据条目后操作');
    return;
  }
  if (!row) {
    row = {
      id: checkedRows.value[0],
    };
  }
  await Layer.readForm({
    title: '编辑应用',
    content: {
      component: form,
      props: { ...row },
    },
  } as any);
}

/**
 * 列表页面列
 */
export const tableColumns = [
  {
    title: '选中',
    key: 'id',
    type: 'selection',
    fixed: 'left',
    width: 50,
    disabled(row: any) {
      return row.name === 'Edward King 3';
    },
  },
  // {
  //   type: 'expand',
  //   expandable: (rowData) => rowData.name !== 'Jim Green',
  //   renderExpand: (rowData) => {
  //   return
  //     return `${rowData.name} is a good guy.`
  //   }
  // },
  {
    title: '字典名称',
    key: 'dictName',
    sorter: 'dictName',
    width: 150,
  },
  {
    title: '字典编码',
    key: 'dictCode',
    sorter: 'dictCode',
    width: 150,
  },
  {
    title: '所属分组',
    key: 'fkDictGroupCode',
    sorter: 'fkDictGroupCode',
    width: 240,
  },
  {
    title: '启用',
    key: 'enabled',
    sorter: 'enabled',
    width: 80,
    render(row: RowData) {
      return h(
        NTag,
        {
          type: enabledTextEnum[row.enabled].style,
        },
        enabledTextEnum[row.enabled].text
      );
    },
  },
  {
    title: '排序',
    key: 'orderIndex',
    sorter: 'orderIndex',
    width: 80,
  },
  {
    title: '允许编辑',
    key: 'allowEdit',
    sorter: 'allowEdit',
    width: 100,
    render(row: RowData) {
      return h(
        NTag,
        {
          type: allowTextEnum[row.allowEdit].style,
        },
        allowTextEnum[row.allowEdit].text
      );
    },
  },
  {
    title: '允许删除',
    key: 'allowDel',
    sorter: 'allowDel',
    width: 100,
    render(row: RowData) {
      return h(
        NTag,
        {
          type: allowTextEnum[row.allowDel].style,
        },
        allowTextEnum[row.allowDel].text
      );
    },
  },

  {
    title: '创建时间',
    key: 'createTime',
    width: 160,
    sorter: 'createTime',
  },
  {
    title: '更新时间',
    key: 'updateTime',
    width: 160,
    sorter: 'updateTime',
  },
  {
    title: '操作',
    key: 'id',
    type: 'id',
    width: 160,
    fixed: 'right',
    render: function (row: any) {
      if (!row.allowDel) {
        noAllowDeleteIds.add(row.id);
      } else if (noAllowDeleteIds.has(row.id)) {
        noAllowDeleteIds.delete(row.id);
      }
      if (!row.allowEdit) {
        noAllowEditIds.add(row.id);
      } else if (noAllowEditIds.has(row.id)) {
        noAllowEditIds.delete(row.id);
      }
      return h(NSpace, [
        h(
          NButton,
          {
            onVnodeMounted: async (vNode: any) => {
              //await checkAuthShow(vNode.el as any, "1P76CZFAXE");
              if (!row.allowEdit) {
                // await authHide(vNode.el);
              }
            },
            type: 'primary',
            text: true,
            disabled: !row.allowEdit,
            onClick: (async (row: any) => {
              await doUpdateModal(row);
            }).bind(null, row),
          },
          '编辑'
        ),
        h(
          NButton,
          {
            // onVnodeMounted: async (vNode: any) => {
            //   if (!row.allowDel) {
            //     await authHide(vNode.el);
            //   }
            // },
            type: 'primary',
            text: true,
            disabled: !row.allowDel,

            onClick: (async (row: any) => {
              await doDeleteModal(row);
            }).bind(null, row),
          },
          '删除'
        ),
      ]);
    },
  },
];
/**
 * 新增和更新校验规则
 */
export const formRules = reactive({
  dictName: [{ required: true, message: '请输入字典名称', trigger: 'blur' }],
  dictCode: [{ required: true, message: '请输入字典编码', trigger: 'blur' }],
  fkDictGroupCode: [{ required: true, message: '请输入所属分组', trigger: 'blur' }],
  enabled: [{ required: true, message: '请输入启用', trigger: 'blur' }],
  allowEdit: [{ required: true, message: '请输入允许编辑', trigger: 'blur' }],
  allowDel: [{ required: true, message: '请输入允许删除', trigger: 'blur' }],
  dictProperties: [],
});
